<?php
/**
 * Post.php
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */

/** Zend db table abstract */
require_once 'Madoqua/Db/Table/Abstract.php';

/** row class */
require_once 'Page/Row.php';

/** url model */
require_once 'Url.php';

/**
 * Blog_Page
 *
 * posts model
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */
class Blog_Page extends Madoqua_Db_Table_Abstract
{
    /**
     * row class
     *
     * @var string
     */
    protected $_rowClass = 'Blog_Page_Row';

    /**
     * table name
     *
     * @var string
     */
    protected $_name = 'page';

    /**
     * generate a slug for a given string
     *
     * @param string $string
     * @param bool $checkExists check for existing slug and add numbers to slug
     * @return string
     */
    public static function slugify($string, $checkExists = false) {
        
        $string = Blog_Url::slugify($string);
        
        if ($checkExists) {
            $model = new Blog_Page();
            $slug = $string;
            $select = $model->select()->where('slug = ?', $slug);
            $x = 2;
            while($model->fetchRow($select) != null) {
                $slug = $string . $x++;
                $select = $model->select()->where('slug = ?', $slug);
            }
            //update if it already exists
            $string = $slug;
        }
        
        return $string;
    }
    
    /**
     * Inserts a new row.
     *
     * @param  array  $data  Column-value pairs.
     * @return mixed         The primary key of the row inserted.
     */
    public function insert(array $data)
    {
        if (empty($data['slug'])) {
            $data['slug'] = Blog_Page::slugify($data['title'], true);
        }
        //update slug if it doesn't exist

        return parent::insert($data);
    }    

    /**
     * fetch a page by slug
     *
     * @param string $slug
     * @return Zend_Db_Table_Row
     */
    public function fetchBySlug($slug)
    {
        return $this->fetchRow($this->select()->where('slug = ?', $slug));
    }

    /**
     * fetch a page by id
     *
     * @param string $id
     * @return Zend_Db_Table_Row
     */
    public function fetchById($id)
    {
        return $this->fetchRow($this->select()->where('id = ?', $id));
    }
}